<section data-type="introduction" id="_introduction">
  <h1>Introduction</h1>
  
  <blockquote data-type="epigraph">
  <p>“Reading about nature is fine, but if a person walks in the woods and listens carefully, they can learn more than what is in books.”</p>
  <p data-type="attribution">— George Washington Carver</p>
  </blockquote>
  
  <p>Here we are: the beginning. Well, almost the beginning. If it’s been a while since you’ve done any programming in JavaScript (or any math, for that matter), this introduction will get your mind back into computational thinking before I approach some of the more difficult and complex material.</p>
  
  <p>In Chapter 1, I’m going to talk about the concept of a vector and how it will serve as the building block for simulating motion throughout this book. But before I take that step, let’s think about what it means for something to simply move around the screen. Let’s begin with one of the best-known and simplest simulations of motion—the random walk.</p>
  
  <section data-type="sect1" id="intro_section1">
  <h2>I.1 Random Walks</h2>
  
  <a data-primary="random walks" data-type="indexterm"></a>
  
  <p>Imagine you are standing in the middle of a balance beam. Every ten seconds, you flip a coin. Heads, take a step forward. Tails, take a step backward. This is a random walk—a path defined as a series of random steps. Stepping off that balance beam and onto the floor, you could perform a random walk in two dimensions by flipping that same coin twice with the following results:</p>
  
  <table>
    <thead>
      <tr>
        <th>Flip 1</th>
        <th>Flip 2</th>
        <th>Result</th>
      </tr>
    </thead>
    <tbody>
      <tr>
        <td>
        <p>Heads</p>
        </td>
        <td>
        <p>Heads</p>
        </td>
        <td>
        <p>Step forward.</p>
        </td>
      </tr>
      <tr>
        <td>
        <p>Heads</p>
        </td>
        <td>
        <p>Tails</p>
        </td>
        <td>
        <p>Step right.</p>
        </td>
      </tr>
      <tr>
        <td>
        <p>Tails</p>
        </td>
        <td>
        <p>Heads</p>
        </td>
        <td>
        <p>Step left.</p>
        </td>
      </tr>
      <tr>
        <td>
        <p>Tails</p>
        </td>
        <td>
        <p>Tails</p>
        </td>
        <td>
        <p>Step backward.</p>
        </td>
      </tr>
    </tbody>
  </table>
  
  <p>Yes, this may seem like a particularly unsophisticated algorithm. Nevertheless, random walks can be used to model phenomena that occur in the real world, from the movements of molecules in a gas to the behavior of a gambler spending a day at the casino. For this book, the random walk is the perfect place to start with the following three goals in mind.</p>
  
  <a data-primary="natural phenomena" data-secondary="modeling with random walks" data-type="indexterm"></a>
  
  <ol>
    <li>
    <p>I need to review a programming concept central to this book—object-oriented programming. The random walker will serve as a template for how I will use object-oriented design to make things that move around a p5.js canvas.</p>
    </li>
    <li>
    <p>The random walk instigates the two questions that I will ask over and over again throughout this book: “How do we define the rules that govern the behavior of our objects?” and then, “How do we implement these rules in JavaScript?”</p>
    </li>
    <li>
    <p>Throughout the book, you’ll periodically need a basic understanding of randomness, probability, and Perlin noise. The random walk will allow me to demonstrate a few key points that will come in handy later.</p>
    </li>
  </ol>
  </section>
  
  <section data-type="sect1" id="intro_section2">
  <h2>I.2 The Random Walker Class</h2>
  
  <a data-primary="object-oriented programming" data-secondary="review of" data-type="indexterm"></a> <a data-primary="Processing" data-secondary="review of object-oriented programming with" data-type="indexterm"></a>
  
  <p>Let’s review a bit of object-oriented programming (OOP) first by building a <code>Walker</code> object. This will be only a cursory review. If you have never worked with OOP before, you may want something more comprehensive; I’d suggest stopping here and reviewing this <a href="https://youtu.be/T-HGdc8L-7w?list=PLRqwX-V7Uu6Zy51Q-x9tMWIv9cueOFTFA">video tutorial on the basics of ES6 classes</a> with p5.js before continuing.</p>
  
  <a data-primary="object" data-secondary="defined" data-type="indexterm"></a> <a data-primary="object-oriented programming" data-secondary="object" data-type="indexterm"></a>
  
  <p>An <strong><em>object</em></strong> in JavaScript is an entity that has both data and functionality. I am looking designing a <code>Walker</code> object that both keeps track of its data (where it exists on the screen) and has the capability to perform certain actions (such as draw itself or take a step).</p>
  
  <a data-primary="class (Processing)" data-secondary="defined" data-type="indexterm"></a> <a data-primary="object-oriented programming" data-secondary="class" data-type="indexterm"></a>
  
  <p>A <strong><em>class</em></strong> is the template for building actual instances of objects. Think of a class as the cookie cutter; the objects are the cookies themselves.</p>
  
  <p>I’ll begin by defining the <code>Walker</code> class—what it means to be a <code>Walker</code> object. The <code>Walker</code> only needs two pieces of data—a number for its x-position and one for its y-position. These are initialized in the “constructor” function, appropriately named <code>constructor</code>. You can think of it as the object’s <code>setup()</code>. There, we’ll initialize the <code>Walker</code> object's starting position (in this case, the center of the window). Also note the use of the keyword <code>this</code> to attach the properties to the newly created object itself.</code></p>
  
  <pre data-code-language="java" data-type="programlisting" class="codesplit">
  class Walker {
    // Objects have a constructor where they are initialized.
    constructor() {
      // Objects have data.
      this.x = width / 2;
      this.y = height / 2;
    }</pre>
  
  <div data-type="note">
    <h2>Code formatting</h2>
    Since the above lines of code above are the first to appear in this book, I'd like to take a moment to highlight a few important conventions I'm using in code.
    <ul>
      <li>Code will always appear in a <code>monospaced font</code>.</li>
      <li>Comments that address what is happening in the code float to the right of the code.</li>
      <li>The light grey highlighting matches the comments with their corresponding lines of code.</li>
      <li>Code that appears broken up by paragraphs of text (like) often appears as unfinished snippets.  For example, the closing bracket — <code>}</code> — for the Walker class does not appear until later below.</li>
    </ul>
  </div>
      
  <a data-primary="class (Processing)" data-secondary="constructor" data-type="indexterm"></a> <a data-primary="constructor" data-type="indexterm"></a>
  
  <a data-primary="class (Processing)" data-secondary="functionality" data-type="indexterm"></a> <a data-primary="functionality" data-type="indexterm"></a>
  
  <p>Finally, in addition to data, classes can be defined with functionality. In this example, a <code>Walker</code> object has two functions. The first one <code>show()</code> the object to display itself (as a black dot). Once again, never forget the <code>this.</code> when references the properties of the object.</p>
  
  <pre data-code-language="java" data-type="programlisting" class="codesplit">
    // Objects have functions.
    show() {
      stroke(0);
      point(this.x, this.y);
    }</pre>
  
  <p>The second function directs the <code>Walker</code> object to take a step. Now, this is where things get a bit more interesting. Remember that floor on which you were taking random steps? Well, now I can use a p5.js canvas in that same capacity. There are four possible steps. A step to the right can be simulated by incrementing <code>x</code> (<code>x++</code>); to the left by decrementing <code>x</code> (<code>x--</code>); forward by going down a pixel (<code>y++</code>); and backward by going up a pixel (<code>y--</code>). How does one pick from these four choices? Earlier I stated that you could flip two coins. In p5.js, however, when you want to randomly choose from a list of options, you can pick a random number using <code>random()</code>.</p>
  
  <a data-primary="random number generators" data-secondary="random() function" data-type="indexterm"></a> <a data-primary="random() function" data-type="indexterm"></a>
  
  <pre data-code-language="java" data-type="programlisting" class="codesplit">
    void step() {
      // 0, 1, 2, or 3
      let choice = floor(random(4));</pre>
  
  <p>The above line of code picks a random floating point number between 0 and 4 and coverts it to an integer (aka whole number) with a result of 0, 1, 2, or 3. Technically speaking, the random number picked can never be 4.0, but rather the highest possibility is 3.999999999 (with as many 9s as there are decimal places); since the <code>floor()</code> function lops off the decimal place, the highest possible <code>integer</code> is 3. Next, the walker takes the appropriate step (left, right, up, or down) depending on which random number was picked.</p>
  
  <pre data-code-language="java" data-type="programlisting" class="codesplit">
      //{!9} The random "choice" determines our step.
      if (choice == 0) {
        x++;
      } else if (choice == 1) {
        x--;
      } else if (choice == 2) {
        y++;
      } else {
        y--;
      }
    }
  }</pre>
  
  <p>Now that I’ve written the class, it’s time to make an actual <code>Walker</code> object in the main sketch—<code>setup()</code> and <code>draw()</code>. Assuming you are looking to model a single random walk, a single global variable.</p>
  
  <pre data-code-language="java" data-type="programlisting" class="codesplit">
  // A Walker object
  let walker;</pre>
  
  <a data-primary="new operator (objects)" data-type="indexterm"></a> <a data-primary="object" data-secondary="new operator" data-type="indexterm"></a>
  
  <p>Then the object is created in <code>setup()</code> by referencing the class name with the <code>new</code> operator.</p>
  
  <div data-type="example">
  <h5>Example I.1: Traditional random walk</h5>
  </div>
  
  <p><em>Each time you see the above Example heading in this book, it means there is a corresponding code example available on <a href="https://github.com/nature-of-code/noc-examples-p5.js">GitHub</a>.</em></p>
  
  <pre data-code-language="java" data-type="programlisting" class="codesplit">
  function setup() {
    createCanvas(640, 360);
    //{!1 .bold} Create the Walker.
    walker = new Walker();
    background(255);
  }</pre>
  
  <p>Finally, during each cycle through <code>draw()</code>, the <code>Walker</code> takes a step and draws a dot.</p>
  
  <pre data-code-language="java" data-type="programlisting" class="codesplit">
  function draw() {
    //{!2 .bold} Call functions on the Walker.
    walker.step();
    walker.display();
  }</pre>
  
  <p>Since the background is drawn once in <code>setup()</code>, rather than clearing it continually each time through <code>draw()</code>,  the trail of the random walk is visible in the canvas.</p>
  
  <figure class="screenshot" data-p5-sketch="https://editor.p5js.org/embed/Syh78gFBz"><img alt="intro ex01" src="intro/intro_ex01.png" />
  <figcaption>&nbsp;</figcaption>
  </figure>
  
  <p>There are a couple improvements that could be made to the random walker. For one, this <code>Walker</code> object’s steps are limited to four options—up, down, left, and right. But any given pixel in the window has eight possible neighbors, and a ninth possibility is to stay in the same place.</p>
  
  <figure id="intro_figure1"><img alt="Figure I.1" src="intro/intro_01.png" />
  <figcaption>Figure I.1</figcaption>
  </figure>
  
  <p>To implement a <code>Walker</code> object that can step to any neighboring pixel (or stay put), I could pick a number between 0 and 8 (nine possible choices). However, another way to write the code would be to pick from three possible steps along the x-axis (-1, 0, or 1) and three possible steps along the y-axis.</p>
  
  <pre data-code-language="java" data-type="programlisting" class="codesplit">
    function step() {
      //{!2} Yields -1, 0, or 1
      let xstep = floor(random(3)) - 1;
      let ystep = floor(random(3)) - 1;
      this.x += xstep;
      this.y += ystep;
    }</pre>
  
  <p>Taking this further, floating point numbers (i.e. decimal numbers) can be used to take a step with a continuous random value between -1 and 1.</p>
  
  <pre data-code-language="java" data-type="programlisting" class="codesplit">
    function step() {
      //{!2} Any floating point number between -1.0 and 1.0
      let xstep = random(-1, 1);
      let ystep = random(-1, 1);
      this.x += xstep;
      this.y += ystep;
    }</pre>
  
  <p>All of these variations on the “traditional” random walk have one thing in common: at any moment in time, the probability that the <code>Walker</code> will take a step in a given direction is equal to the probability that the <code>Walker</code> will take a step in any direction. In other words, if there are four possible steps, there is a 1 in 4 (or 25%) chance the <code>Walker</code> will take any given step. With nine possible steps, it’s a 1 in 9 (or ~11.1%) chance.</p>
  
  <a data-primary="random number generators" data-secondary="uniform number distributions and" data-type="indexterm"></a> <a data-primary="uniform number distributions" data-type="indexterm"></a>
  
  <p>Conveniently, this is how the <code>random()</code> function works. p5’s random number generator (which operates behind the scenes) produces what is known as a “uniform” distribution of numbers. You can test this distribution with a sketch that counts each time a random number is picked and graphs it as the height of a rectangle.</p>
  
  <figure class="screenshot" data-p5-sketch="https://editor.p5js.org/embed/BJHTAHUwe"><img alt="intro ex02" src="intro/intro_ex02.png" />
  <figcaption>&nbsp;</figcaption>
  </figure>
  
  <div data-type="example">
  <h5>Example I.2: Random number distribution</h5>
  </div>
  
  <pre data-code-language="java" data-type="programlisting" class="codesplit">
  //{!1} An array to keep track of how often random numbers are picked
  let randomCounts = [];
  
  function setup() {
    createCanvas(640, 240);
    for (let i = 0; i &lt; 20; i++) {
      randomCounts[i] = 0; 
    }
  }
  
  function draw() {
    background(255);
  
    //{!2} Pick a random number and increase the count.
    let index = floor(random(randomCounts.length));
    randomCounts[index]++;
  
    stroke(0);
    fill(175);
    let w = width / randomCounts.length;
    //{!3 .offset-top} Graphing the results
    for (let x = 0; x &lt; randomCounts.length; x++) {
      rect(x * w, height - randomCounts[x], w - 1, randomCounts[x]);
    }</pre>
  
  <p>Notice how each bar of the graph above differs slightly in height. The sample size (i.e. the number of random numbers picked) is small and there are some occasional discrepancies where certain numbers are picked more often. Over time, with a good random number generator, this would even out.</p>
  
  <a data-primary="pseudo-random numbers" data-type="indexterm"></a> <a data-primary="random number generators" data-secondary="pseudo-random numbers" data-type="indexterm"></a>
  
  <div data-type="note">
  <h2>Pseudo-Random Numbers</h2>
  
  <p>The random numbers from the <code>random()</code> function are not truly random; they are known as “pseudo-random.” They are the result of a mathematical function that simulates randomness. This function would yield a pattern over time, but that time period is so long that for the examples in this book, it’s just as good as pure randomness!</p>
  </div>
  
  <div data-type="exercise" id="intro_exercise1">
  <h5>Exercise I.1</h5>
  
  <p>Create a random walker that has a tendency to move down and to the right. (The solution follows in the next section.)</p>
  </div>
  </section>
  
  <section data-type="sect1" id="intro_section3">
  <h2>I.3 Probability and Non-Uniform Distributions</h2>
  
  <a data-primary="natural phenomena" data-secondary="modeling with the random() function" data-type="indexterm"></a> <a data-primary="non-uniform distributions" data-secondary="probability and" data-type="indexterm"></a> <a data-primary="distributions" data-secondary="non-uniform" data-tertiary="probability and" data-type="indexterm"></a> <a data-primary="probability" data-secondary="non-uniform distributions and" data-type="indexterm"></a> <a data-primary="random number generators" data-secondary="non-uniform distributions" data-tertiary="creating" data-type="indexterm"></a> <a data-primary="random() function" data-secondary="natural phenomena" data-tertiary="modeling with" data-type="indexterm"></a>
  
  <p>Remember when you first started programming with p5.js? Perhaps you wanted to draw a lot of circles on the screen. So you said to yourself: “Oh, I know. I’ll draw all these circles at random positions, with random sizes and random colors.” In a computer graphics system, it’s often easiest to seed a system with randomness. In this book, however, I am looking to build systems modeled on what we see in nature. Defaulting to randomness is not a particularly thoughtful solution to a design problem—in particular, the kind of problem that involves creating an organic or natural-looking simulation.</p>
  
  <a data-primary="probability of the fittest" data-type="indexterm"></a>
  
  <p>With a few tricks, I can use the <code>random()</code> function to produce “non-uniform” distributions of random numbers. This will come in handy throughout the book for a variety of scenarios. In chapter 9's genetic algorithms, for example, I’ll need a methodology for performing “selection”—which members of the population should be selected to pass their DNA to the next generation? This is akin to the Darwinian concept of “survival of the fittest”? Say you have a population of monkeys evolving. Not every monkey will have an equal chance of reproducing. To simulate Darwinian natural selection, you can’t simply pick two random monkeys to be parents. The more “fit” ones should be more likely to be chosen. This could vbe considered the “probability of the fittest.” For example, a particularly fast and strong monkey might have a 90% chance of procreating, while a weaker one has only a 10% chance.</p>
  
  <a data-primary="probability" data-type="indexterm"></a>
  
  <p>Let’s pause here and take a look at probability’s basic principles. First I’ll examine single event probability, i.e. the likelihood that a given event will occur.</p>
  
  <p>If you have a system with a certain number of possible outcomes, the probability of the occurrence of a given event equals the number of outcomes that qualify as that event divided by the total number of all possible outcomes. A coin toss is a simple example—it has only two possible outcomes, heads or tails. There is only one way to flip heads. The probability that the coin will turn up heads, therefore, is one divided by two: 1/2 or 50%.</p>
  
  <p>Take a deck of fifty-two cards. The probability of drawing an ace from that deck is:</p>
  
  <p><span class="formula">number of aces / number of cards = 4 / 52 = 0.077 = ~ 8%</span></p>
  
  <p>The probability of drawing a diamond is:</p>
  
  <p><span class="formula">number of diamonds / number of cards = 13 / 52 = 0.25 = 25%</span></p>
  
  <p>We can also calculate the probability of multiple events occurring in sequence. To do this, multiply the individual probabilities of each event.</p>
  
  <p>The probability of a coin turning up heads three times in a row is:</p>
  
  <p><span class="formula">(1/2) * (1/2) * (1/2) = 1/8 (or 0.125)</span></p>
  
   <p>...meaning that a coin will turn up heads three times in a row one out of eight times on average. For example if you flipped a coin three times in a row 500 times, you would expect to see an outcome of three consecutive heads an average of one eighth of the time or ~63 times.</p>
  
  <div data-type="exercise" id="intro_exercise2">
  <h5>Exercise I.2</h5>
  
  <p>What is the probability of drawing two aces in a row from a deck of fifty-two cards?</p>
  </div>
  
  <a data-primary="arrays" data-secondary="custom distributions" data-tertiary="creating with" data-type="indexterm"></a> <a data-primary="distributions" data-secondary="non-uniform" data-tertiary="creating with arrays" data-type="indexterm"></a> <a data-primary="non-uniform distributions" data-secondary="creating with arrays" data-type="indexterm"></a> <a data-primary="random() function" data-secondary="non-uniform distributions" data-tertiary="creating with" data-type="indexterm"></a>
  
  <p>There are a couple of ways in which you can use the <code>random()</code> function with probability in code. One technique is to fill an array with numbers—some of which are repeated—then choose random elements from that array and generate events based on those choices.</p>
  
  <pre data-code-language="java" data-type="programlisting" class="codesplit">
  // 1 and 3 are stored in the array twice, making them more likely to be picked than 2.
  let stuff = {1, 1, 2, 3, 3};
  // Picking a random element from an array
  let value = random(stuff);
  print(value);</pre>
  
  <p>Running this code will produce a 40% chance of printing the value 1, a 20% chance of printing 2, and a 40% chance of printing 3.</p>
  
  <p>You can also ask for a random number (let’s make it simple and just consider random floating point values between 0 and 1) and allow an event to occur only if our random number is within a certain range. For example:</p>
  
  <pre data-code-language="java" data-type="programlisting" class="codesplit">
  // A probability of 10%
  let probability = 0.1;
  // A random floating point between 0 and 1
  let r = random(1);
  // If the random number is less than 0.1, sing!
  if (r &lt; prob) {
    print("Sing!");
  }</pre>
  
  <p>This method can also be applied to multiple outcomes. Let’s say that singing has a 60% chance of happening, dancing, a 10% chance, and sleeping, a 30% chance. This can be implemented by picking a random number and seeing into what range it falls.</p>
  
  <ul>
    <li>
    <p><em>between 0.00 and 0.60 (60%) → Singing</em></p>
    </li>
    <li>
    <p><em>between 0.60 and 0.70 (10%) → Dancing</em></p>
    </li>
    <li>
    <p><em>between 0.70 and 1.00 (30%) → Sleeping</em></p>
    </li>
  </ul>
  
  <pre data-code-language="java" data-type="programlisting" class="codesplit">
  let num = random(1);
  
  // If random number is less than 0.6
  if (num &lt; 0.6) {
    print("Sing!");
  // Between 0.6 and 0.7
  } else if (num &lt; 0.7) {
    print("Dance!");
  // Greater than 0.7
  } else {
    print("Sleep!");
  }</pre>
  
  <p>The above methodology can be used to create a random walker that tends to move in a particular direction. Here is an example of a <code>Walker</code> with the following probabilities:</p>
  
  <ul>
    <li>
    <p><em>chance of moving up: 20%</em></p>
    </li>
    <li>
    <p><em>chance of moving down: 20%</em></p>
    </li>
    <li>
    <p><em>chance of moving left: 20%</em></p>
    </li>
    <li>
    <p><em>chance of moving right: 40%</em></p>
    </li>
  </ul>
  
  <figure class="screenshot" data-p5-sketch="https://editor.p5js.org/embed/SkPQJIUwx"><img alt="intro ex03" src="intro/intro_ex03.png" />
  <figcaption>intro ex03&nbsp;</figcaption>
  </figure>
  
  <div data-type="example">
  <h5>Example I.3: Walker that tends to move to the right</h5>
  </div>
  
  <pre data-code-language="java" data-type="programlisting" class="codesplit">
    function step() {
  
      let r = random(1);
      //{!2} A 40% chance of moving to the right!
      if (r &lt; 0.4) {
        x++;
      } else if (r &lt; 0.6) {
        x--;
      } else if (r &lt; 0.8) {
        y++;
      } else {
        y--;
      }
    }</pre>
  
  <div data-type="exercise" id="intro_exercise3">
  <h5>Exercise I.3</h5>
  
  <p>Create a random walker with dynamic probabilities. For example, can you give it a 50% chance of moving in the direction of the mouse?</p>
  </div>
  </section>
  
  <section data-type="sect1" id="intro_section4">
  <h2>I.4 A Normal Distribution of Random Numbers</h2>
  
  <p>Let’s go back to that population of simulated monkeys. Your program generates a thousand <code>Monkey</code> objects, each with a height value between 200 and 300 (as this is a world of monkeys that have heights between 200 and 300 pixels).</p>
  
  <pre data-code-language="java" data-type="programlisting" class="codesplit">
  let h = random(200, 300);</pre>
  
  <a data-primary="distributions" data-secondary="normal" data-type="indexterm"></a> <a data-primary="probability" data-secondary="normal distributions" data-type="indexterm"></a>
  
  <p>Is this an accurate algorithm for creating a population of monkey heights? Think of a crowded sidewalk in New York City. Pick any person off the street and it may appear that their height is random. Nevertheless, it’s not the kind of random that <code>random()</code> produces by default. People’s heights are not uniformly distributed; there are many more people of average height than there are very tall or very short ones. To simulate a more “natural“ distribution, the values picked for the monkeys' heights should mostly be around average (250 pixels), yet still be, on occasion, very short or very tall.</p>
  
  <a data-primary="bell curve" data-type="indexterm"></a> <a data-primary="bell curve" data-secondary="mean and" data-type="indexterm"></a> <a data-primary="Gauss" data-secondary="Carl Friedrich" data-type="indexterm"></a> <a data-primary="Gaussian distribution" data-type="indexterm"></a> <a data-primary="Laplace" data-secondary="Pierre-Simon" data-type="indexterm"></a> <a data-primary="Laplacian distribution" data-type="indexterm"></a> <a data-primary="mean" data-type="indexterm"></a> <a data-primary="normal distribution" data-type="indexterm"></a> <a data-primary="probability" data-secondary="mean" data-type="indexterm"></a>
  
  <p>One of the most famous examples of a distribution of values that cluster around an average (referred to as the “mean”) is called a “normal” distribution.  It is also sometimes referred to as the Gaussian distribution (named for mathematician Carl Friedrich Gauss).</p>
  
  <p>When you graph this distribution, you get something that looks like the following, informally known as a bell curve:</p>
  
  <figure class="two-col" id="intro_figure2"><img alt="Figure I.2" src="intro/intro_02.png" />
  <figcaption>Figure I.2</figcaption>
  </figure>
  
  <figure class="two-col" id="intro_figure3"><img alt="Figure I.3" src="intro/intro_03.png" />
  <figcaption>Figure I.3</figcaption>
  </figure>
  
  <a data-primary="mu (μ)" data-type="indexterm"></a> <a data-primary="sigma (σ)" data-type="indexterm"></a> <a data-primary="probability" data-secondary="standard deviation" data-type="indexterm"></a> <a data-primary="standard deviation" data-type="indexterm"></a>
  
  <p>The curve is generated by a mathematical function that defines the probability of any given value occurring as a function of the mean (often written as &mu;, the Greek letter <em>mu</em>) and standard deviation (&sigma;, the Greek letter <em>sigma</em>).</p>
  
  <p>The mean is pretty easy to understand. In the case of our height values between 200 and 300, you probably have an intuitive sense of the mean (i.e. average) as 250. However, what if I were to say that the standard deviation is 3? Or 15? What does this mean for the numbers? The graphs above should give you a hint. Figure I.2 shows the distribution with a very low standard deviation, where the majority of the values pile up around the mean. Figure I.3 shows us a higher standard deviation, where the values are more evenly spread out from the average.</p>
  
  <p>The numbers work out as follows: Given a population, 68% of the members of that population will have values in the range of one standard deviation from the mean, 95% within two standard deviations, and 99.7% within three standard deviations. Given a standard deviation of 5 pixels, only 0.3% of the monkey heights will be less than 235 pixels (three standard deviations below the mean of 250) or greater than 265 pixels (three standard deviations above the mean of 250).</p>
  
  <div data-type="note">
  <h2>Calculating Mean and Standard Deviation</h2>
  
  <p>Consider a class of ten students who receive the following scores (out of 100) on a test:</p>
  
  <p><em>85, 82, 88, 86, 85, 93, 98, 40, 73, 83</em></p>
  
  <p><strong><em>The mean is the average: 81.3</em></strong></p>
  
  <a data-primary="standard deviation" data-secondary="calculating" data-type="indexterm"></a> <a data-primary="standard deviation" data-secondary="variance" data-type="indexterm"></a> <a data-primary="variance" data-type="indexterm"></a>
  
  <p>The standard deviation is calculated as the square root of the average of the squares of deviations around the mean. In other words, take the difference from the mean for each person and square it (aka “variance”). Calculate the average of all these values, take the square root, and you have the standard deviation.</p>
  
  <table>
    <thead>
      <tr>
        <th>Score</th>
        <th>Difference from Mean</th>
        <th>Variance</th>
      </tr>
    </thead>
    <tfoot>
      <tr>
        <td>&nbsp;</td>
        <td>
        <p><strong>Average Variance:</strong></p>
        </td>
        <td>
        <p>228.81</p>
        </td>
      </tr>
    </tfoot>
    <tbody>
      <tr>
        <td>
        <p>85</p>
        </td>
        <td>
        <p>85 - 81.3 = 3.7</p>
        </td>
        <td>
        <p>(3.7)<sup>2</sup> = 13.69</p>
        </td>
      </tr>
      <tr>
        <td>
        <p>40</p>
        </td>
        <td>
        <p>40 - 81.3 = -41.3</p>
        </td>
        <td>
        <p>(-41.3)<sup>2</sup> = 1,705.69</p>
        </td>
      </tr>
      <tr>
        <td>
        <p>etc.</p>
        </td>
        <td>&nbsp;</td>
        <td>&nbsp;</td>
      </tr>
    </tbody>
  </table>
  
  <p><strong><em>The standard deviation is the square root of the average variance: 15.13</em></strong></p>
  </div>
  
  <a data-primary="Processing" data-secondary="Random class" data-type="indexterm"></a> <a data-primary="Random class (Processing)" data-type="indexterm"></a>
  
  <p>Luckily for you, to use a normal distribution of random numbers in a p5.js sketch, you don’t have to do any of these calculations. Instead, the <code>randomGaussian()</code> function returns random numbers with a normal distribution.</p>
  
  <a data-primary="randomGaussian() function" data-type="indexterm"></a>
  
  <pre data-code-language="java" data-type="programlisting" class="codesplit">
  function draw() {
    //{!1} Asking for a Gaussian random number.
    let num = randomGaussian();
  }</pre>
  
  <p>Here’s the thing. What are we supposed to do with this value? What if we wanted to use it, for example, to assign the x-position of a shape we draw on screen?</p>
  
  <a data-primary="randomGaussian() function" data-secondary="default mean/standard deviation settings of" data-type="indexterm"></a>
  
  <p>By default, the <code>randomGaussian()</code> function returns a normal distribution of random numbers with the following parameters: <em>a mean of zero</em> and <em>a standard deviation of one</em>. Let’s say you want a mean of 320 (the center horizontal pixel in a window of width 640) and a standard deviation of 60 pixels. The parameters can be adjusted by passing in two arguments, the mean followed by the standard deviation. </p>
  
  <figure class="screenshot" data-p5-sketch="https://editor.p5js.org/embed/S120y8Uwx"><img alt="intro ex04" src="intro/intro_ex04.png" />
  <figcaption>&nbsp;</figcaption>
  </figure>
  
  <div data-type="example">
  <h5>Example I.4: Gaussian distribution</h5>
  </div>
  
  <pre data-code-language="java" data-type="programlisting" class="codesplit">
  void draw() {
    //{!1} Note that randomGaussian() without arguments returns a value between 0 and 1.
    float x = randomGaussian(60, 320);
    noStroke();
    fill(0,10);
    ellipse(x, 180, 16, 16);
  }</pre>
  

  <p>I'll note that while it's convenient to pass in the arguments, the math for this is quite simple and just involves multiplying a normalized value between 0 and 1 by the standard deviation and adding it to the mean.
  </p>
  
  <pre data-code-language="java" data-type="programlisting" class="codesplit">
  let x = 60 * randomGaussian() + 320;</pre>

  <p>By drawing the ellipses on top of each other with some transparency, you can begin to see see the distribution. The darkest spot is near the center, where most of the values cluster, but every so often circles are drawn farther to the right or left of the center.</p>
  
  <div data-type="exercise" id="intro_exercise4">
  <h5>Exercise I.4</h5>
  
  <p>Consider a simulation of paint splatter drawn as a collection of colored dots. Most of the paint clusters around a central position, but some dots do splatter out towards the edges. Can you use a normal distribution of random numbers to generate the positions of the dots? Can you also use a normal distribution of random numbers to generate a color palette? Try attaching a slider to standard deviation.</p>
  </div>
  
  <a data-primary="random walks" data-secondary="Gaussian" data-type="indexterm"></a>
  
  <div data-type="exercise" id="intro_exercise5">
  <h5>Exercise I.5</h5>
  
  <p>A Gaussian random walk is defined as one in which the step size (how far the object moves in a given direction) is generated with a normal distribution. Implement this variation of the random walk.</p>
  </div>
  </section>
  
  <section data-type="sect1" id="intro_section5">
  <h2>I.5 A Custom Distribution of Random Numbers</h2>
  
  <a data-primary="distributions" data-secondary="custom" data-type="indexterm"></a> <a data-primary="Lévy flight" data-type="indexterm"></a> <a data-primary="non-uniform distributions" data-secondary="custom" data-type="indexterm"></a> <a data-primary="distributions" data-secondary="non-uniform" data-tertiary="custom" data-type="indexterm"></a> <a data-primary="oversampling" data-type="indexterm"></a> <a data-primary="random number generators" data-secondary="custom distributions" data-tertiary="creating" data-type="indexterm"></a> <a data-primary="random walks" data-secondary="Lévy flight" data-type="indexterm"></a> <a data-primary="random walks" data-secondary="oversampling" data-type="indexterm"></a>
  
  <p>There will come a time in your life when you do not want a uniform distribution of random values, or a Gaussian one. Let’s imagine for a moment that you are a random walker in search of food. Moving randomly around a space seems like a reasonable strategy for finding something to eat. After all, you don’t know where the food is, so you might as well search randomly until you find it. The problem, as you may have noticed, is that random walkers return to previously visited positions many times (this is known as “oversampling”). One strategy to avoid such a problem is to, every so often, take a very large step. This allows the walker to forage randomly around a specific position while periodically jumping very far away to reduce the amount of oversampling. This variation on the random walk (known as a Lévy flight) requires a custom set of probabilities. Though not an exact implementation of a Lévy flight, one could state the probability distribution as follows: the longer the step, the less likely it is to be picked; the shorter the step, the more likely.</p>
  
  <p>Earlier in this prologue, I wrote that you could generate custom probability distributions by filling an array with values (some duplicated so that they would be picked more frequently) or by testing the result of <code>random()</code>. A Lévy flight could be implemented with a 1% chance of the walker taking a large step.</p>
  
  <a data-primary="arrays" data-secondary="Lévy flights" data-tertiary="implementing with" data-type="indexterm"></a> <a data-primary="Lévy flight" data-secondary="implementing with arrays" data-type="indexterm"></a>
  
  <pre data-code-language="java" data-type="programlisting" class="codesplit">
  let r = random(1);
  //{$3} A 1% chance of taking a large step
  if (r < 0.01) {
    xstep = random(-100, 100);
    ystep = random(-100, 100);
  } else {
    xstep = random(-1, 1);
    ystep = random(-1, 1);
  }</pre>
  
  <a data-primary="Lévy flight" data-secondary="implementing with qualifying random values" data-type="indexterm"></a>
  
  <p>However, this reduces the probabilities to a fixed number of options. What if you wanted to make a more general rule—the higher a number, the more likely it is to be picked? 3.145 would be more likely to be picked than 3.144, even if that likelihood is just a tiny bit greater. In other words, if <code>x</code> is the random number, the  likelihood of it being picked could be mapped to the y-axis with the function <code>y = x</code>.</p>
  
  <figure id="intro_figure4"><img alt="Figure I.4" src="intro/intro_04.png" />
  <figcaption>Figure I.4</figcaption>
  </figure>
  
  <p>If we can figure out how to generate a distribution of random numbers according to the above graph, then we will be able to apply the same methodology to any curve for which we have a formula.</p>
  
  <a data-primary="non-uniform distributions" data-secondary="qualifying random values" data-type="indexterm"></a> <a data-primary="distributions" data-secondary="non-uniform" data-tertiary="qualifying random values" data-type="indexterm"></a> <a data-primary="qualifying random values" data-type="indexterm"></a>
  
  <p>One solution is to pick two random numbers instead of one. The first random number is just that, a random number. The second one, however, is what we’ll call a “qualifying random value.” It will tell us whether to use the first one or throw it away and pick another one. Numbers that have an easier time qualifying will be picked more often, and numbers that rarely qualify will be picked infrequently. Here are the steps (for now, let’s consider only random values between 0 and 1):</p>
  
  <ol>
    <li>
    <p>Pick a random number: R1</p>
    </li>
    <li>
    <p>Compute a probability P that R1 should qualify. Let’s try: P = R1.</p>
    </li>
    <li>
    <p>Pick another random number: R2</p>
    </li>
    <li>
    <p>If R2 is less than P, then we have found our number—R1!</p>
    </li>
    <li>
    <p>If R2 is not less than P, go back to step 1 and start over.</p>
    </li>
  </ol>
  
  <p>Here we are saying that the likelihood that a random value will qualify is equal to the random number itself. Let’s say we pick 0.1 for R1. This means that R1 will have a 10% chance of qualifying. If we pick 0.83 for R1 then it will have a 83% chance of qualifying. The higher the number, the greater the likelihood that we will actually use it.</p>
  
  <a data-primary="Monte Carlo method" data-type="indexterm"></a> <a data-primary="non-uniform distributions" data-secondary="Monte Carlo method" data-type="indexterm"></a> <a data-primary="distributions" data-secondary="non-uniform" data-tertiary="Monte Carlo method" data-type="indexterm"></a> <a data-primary="qualifying random values" data-secondary="Monte Carlo method" data-type="indexterm"></a>
  
  <p>Here is a function (named for the accept-reject algorithm, a type of Monte Carlo method, which was named for the Monte Carlo casino) that implements the above algorithm, returning a random value between 0 and 1.</p>
  
  <figure class="screenshot" data-pde="______"><img alt="intro ex05" src="intro/intro_ex05.png" />
  <figcaption>&nbsp;</figcaption>
  </figure>
  
  <div data-type="example">
  <h5>Example I.5: Accept-Reject distribution</h5>
  </div>
  
  <pre data-code-language="java" data-type="programlisting" class="codesplit">
  function acceptreject() {
    // We do this “forever” until we find a qualifying random value.
    while (true) {
      // Pick a random value.
      let r1 = random(1);
      // Assign a probability.
      let probability = r1;
      // Pick a second random value.
      let r2 = random(1);
  
      //{!3} Does it qualify?  If so, we’re done!
      if (r2 < probability) {
        return r1;
      }
    }
  }</pre>
  
  <div data-type="exercise" id="intro_exercise6">
  <h5>Exercise I.6</h5>
  
  <p>Use a custom probability distribution to vary the size of a step taken by the random walker. The step size can be determined by influencing the range of values picked. Can you map the probability to a quadratic function—i.e. making the likelihood that a value is picked equal to the value squared?</p>
  
  <pre data-code-language="java" data-type="programlisting" class="codesplit">
    //{!3} A uniform distribution of random step sizes. Change this!
    let step = 10;
    let stepx = random(-step, step);
    let stepy = random(-step, step);
  
    x += stepx;
    y += stepy;</pre>
  
  <p>(Later we’ll see how to do this more efficiently using vectors.)</p>
  </div>
  </section>
  
  <section data-type="sect1" id="intro_section6">
  <h2>I.6 Perlin Noise (A Smoother Approach)</h2>
  
  <a data-primary="natural phenomena" data-secondary="Perlin noise and" data-type="indexterm"></a> <a data-primary="non-uniform distributions" data-secondary="Perlin noise" data-type="indexterm"></a> <a data-primary="distributions" data-secondary="non-uniform" data-tertiary="Perlin noise" data-type="indexterm"></a> <a data-primary="Perlin noise" data-secondary="natural phenomena" data-tertiary="modeling with" data-type="indexterm"></a> <a data-primary="&lt;em&gt;Tron&lt;/em&gt; (1982)" data-type="indexterm"></a>
  
  <p>A good random number generator produces numbers that have no relationship and show no discernible pattern. As we are beginning to see, a little bit of randomness can be a good thing when programming organic, lifelike behaviors. However, randomness as the single guiding principle is not necessarily natural. An algorithm known as “Perlin noise,” named for its inventor Ken Perlin, takes this concept into account. Perlin developed the noise function while working on the original <em>Tron</em> movie in the early 1980s; it was designed to create procedural textures for computer-generated effects. In 1997 Perlin won an Academy Award in technical achievement for this work. Perlin noise can be used to generate various effects with natural qualities, such as clouds, landscapes, and patterned textures like marble.</p>
  
  <a data-primary="naturally ordered sequence of numbers" data-type="indexterm"></a> <a data-primary="pseudo-random numbers" data-secondary="Perlin noise and" data-type="indexterm"></a>
  
  <p>Perlin noise has a more organic appearance because it produces a naturally ordered (“smooth”) sequence of pseudo-random numbers. The graph on the left below shows Perlin noise over time, with the x-axis representing time; note the smoothness of the curve. The graph on the right shows pure random numbers over time. (The code for generating these graphs is available in the accompanying book downloads.)</p>
  
  <figure class="two-col"><img alt="Figure I.5: Noise" src="intro/intro_05.png" />
  <figcaption>Figure I.5: Noise&nbsp;</figcaption>
  </figure>
  
  <figure class="two-col"><img alt="Figure I.6: Random" src="intro/intro_06.png" />
  <figcaption>Figure I.6: Random&nbsp;</figcaption>
  </figure>
  
  <a data-primary="noise() function (Processing)" data-type="indexterm"></a> <a data-primary="Perlin noise" data-secondary="noise() function (Processing)" data-type="indexterm"></a> <a data-primary="Processing" data-secondary="noise() function" data-type="indexterm"></a>
  
  <p>p5.js has a built-in implementation of the Perlin noise algorithm: the function <code>noise()</code>. The <code>noise()</code> function takes one, two, or three arguments, as noise is computed in one, two, or three dimensions. Let’s start by looking at one-dimensional noise.</p>
  
  <a data-primary="noiseDetail() function (Processing)" data-type="indexterm"></a> <a data-primary="Processing" data-secondary="noiseDetail() function" data-type="indexterm"></a>
  
  <div data-type="note">
  <h2 id="noise-detail">Noise Detail</h2>
  
  <p>The p5.js <a href="https://p5js.org/reference/#/p5/noise">noise reference</a> explains that noise is calculated over several “octaves.” Calling the <a href="https://p5js.org/reference/#/p5/noiseDetail"><code>noiseDetail()</code></a> function changes both the number of octaves and their importance relative to one another. This in turn changes quality of the noise values produced.</p>
  
  <p>You can learn more about the history of Perlin noise <a href="https://mrl.nyu.edu/~perlin/doc/oscar.html">Ken Perlin's website</a>.</p>
  </div>
  
  <p>Let's begin exploring noise by drawing a circle on a canvas at a random x-position.</p>
  
  <pre data-code-language="java" data-type="programlisting" class="codesplit">
  // A random x-position
  let x = random(0, width);
  ellipse(x, 180, 16, 16);</pre>
  
  <p>Now, instead of a random x-position, I want a Perlin noise x-position that is “smoother.” You might think that all you need to do is replace <code>random()</code> with <code>noise()</code>, i.e.</p>
  
  <pre data-code-language="java" data-type="programlisting" class="codesplit">
  //{.line-through} A noise x-position?
  let x = noise(0, width);</pre>
  
  <a data-primary="noise() function (Processing)" data-secondary="arguments for" data-type="indexterm"></a>
  
  <p>While conceptually this is exactly what we want to do—calculate an x-value that ranges between 0 and the width according to Perlin noise—this is not the correct implementation. While the arguments to the <code>random()</code> function specify a range of values between a minimum and a maximum, <code>noise()</code> does not work this way. Instead, the output range is fixed—it always returns a value between 0 and 1. You’ll see in a moment that you can get around this easily with p5’s <code>map()</code> function, but first let‘s examine what exactly <code>noise()</code> expects us to pass in as an argument.</p>
  
  <p>One-dimensional Perlin noise can be thought of as a linear sequence of values over time. For example:</p>
  
  <table>
    <thead>
      <tr>
        <th>Time</th>
        <th>Noise Value</th>
      </tr>
    </thead>
    <tbody>
      <tr>
        <td>
        <p>0</p>
        </td>
        <td>
        <p>0.365</p>
        </td>
      </tr>
      <tr>
        <td>
        <p>1</p>
        </td>
        <td>
        <p>0.363</p>
        </td>
      </tr>
      <tr>
        <td>
        <p>2</p>
        </td>
        <td>
        <p>0.363</p>
        </td>
      </tr>
      <tr>
        <td>
        <p>3</p>
        </td>
        <td>
        <p>0.364</p>
        </td>
      </tr>
      <tr>
        <td>
        <p>4</p>
        </td>
        <td>
        <p>0.366</p>
        </td>
      </tr>
    </tbody>
  </table>
  
  <p>Now, in order to access a particular noise value, a "moment in time" must be specified and passed to the <code>noise()</code> function. For example:</p>
  
  <pre data-code-language="java" data-type="programlisting" class="codesplit">
  let n = noise(3);</pre>
  
  <p>According to the above table, <code>noise(3)</code> returns 0.364. The next step in exploring noise is to use a variable for time and ask for a noise value continuously in <code>draw()</code>.</p>
  
  <pre data-code-language="java" data-type="programlisting" class="codesplit">
  let t = 3;
  
  function draw() {
    //{!1} We need the noise value for a specific moment in time.
    let n = noise(t);
    print(n);
  }</pre>
  
  <p>The above code results in the same value printed over and over. This happens because I am asking for the result of the <code>noise()</code> function at the same point in time—3—over and over. If the time variable <code>t</code> increments, however, I’ll get a different result.</p>
  
  <pre data-code-language="java" data-type="programlisting" class="codesplit">
  //{!1} Typically we would start with an offset of time = 0, though this is arbitrary.
  let t = 0;
  
  function draw() {
    let n = noise(t);
    print(n);
    //{!1} Now, we move forward in time!
    t += 0.01;
  }</pre>
  
  <p>How quickly <code>t</code> increments also affects the smoothness of the noise. Large jumps in time that skip ahead through the noise space produce values that are less smooth, and more random.</p>
  
  <figure id="intro_figure7"><img alt="Figure I.7" src="intro/intro_07.png" />
  <figcaption>Figure I.7</figcaption>
  </figure>
  
  <p>Try running the code several times, incrementing <code>t</code> by 0.01, 0.02, 0.05, 0.1, 0.0001, and you will see different results.</p>
  
  <section data-type="sect2" id="_mapping_noise">
  <h3>Mapping Noise</h3>
  
  <a data-primary="map() function (Processing)" data-type="indexterm"></a> <a data-primary="Perlin noise" data-secondary="map() function" data-type="indexterm"></a>
  
  <p>Now it’s time to answer the question of what to do with the noise value. Once you have the value with a range between 0 and 1, it’s up to you to map that range accordingly. The easiest way to do this is with p5’s <code>map()</code> function. The <code>map()</code> function takes five arguments. First is the value you want to map, in this case <code>n</code>. This is followed by the value’s current range (minimum and maximum), followed by the desired range.</p>
  
  <figure id="intro_figure8"><img alt="Figure I.8" src="intro/intro_08.png" />
  <figcaption>Figure I.8</figcaption>
  </figure>
  
  <p>In this case, while noise has a range between 0 and 1, I’d like to draw a circle with a range between 0 and the canvas’s width.</p>
  
  <pre data-code-language="java" data-type="programlisting" class="codesplit">
  let t = 0;
  
  function draw() {
    let n = noise(t);
    //{!1} Using map() to customize the range of Perlin noise
    let x = map(n, 0, 1, 0, width);
    ellipse(x, 180, 16, 16);
  
    t += 0.01;
  }</pre>
  
  <p>The exact same logic can be applied to the random walker, assigning both its x- and y-values according to Perlin noise.</p>
  
  <figure class="screenshot" data-p5-sketch="https://editor.p5js.org/embed/SkuNg88Dx"><img alt="intro ex06" src="intro/intro_ex06.png" />
  <figcaption>&nbsp;</figcaption>
  </figure>
  
  <div data-type="example">
  <h5>Example I.6: Perlin noise walker</h5>
  </div>
  
  <pre data-code-language="java" data-type="programlisting" class="codesplit">
  class Walker {
    Walker() {
      this.tx = 0;
      this.ty = 10000;
    }
  
    void step() {
      //{!2} x- and y-position mapped from noise
      this.x = map(noise(tx), 0, 1, 0, width);
      this.y = map(noise(ty), 0, 1, 0, height);
  
      //{!2} Move forward through “time.”
      this.tx += 0.01;
      this.ty += 0.01;
    }
  }</pre>
  
  <p>Notice how the above example requires a new pair of variables: <code>tx</code> and <code>ty</code>. This is because we need to keep track of two time variables, one for the x-position of the <code>Walker</code> object and one for the y-position. But there is something a bit odd about these variables. Why does <code>tx</code> start at 0 and <code>ty</code> at 10,000? While these numbers are arbitrary choices, I have intentionally initialized the two time variables this way. This is because the noise function is deterministic: it gives you the same result for a specific time <code>t</code> each and every time. If I asked for the noise value at the same time <code>t</code> for both <code>x</code> and <code>y</code>, then <code>x</code> and <code>y</code> would always be equal, meaning that the <code>Walker</code> object would only move along a diagonal. Instead, I use two different parts of the noise space, starting at 0 for <code>x</code> and 10,000 for <code>y</code> so that <code>x</code> and <code>y</code> appear to act independently of each other.</p>
  
  <figure id="intro_figure9"><img alt="Figure I.9" src="intro/intro_09.png" />
  <figcaption>Figure I.9</figcaption>
  </figure>
  
  <p>In truth, there is no actual concept of time at play here. It’s a useful metaphor to help us understand how the noise function works, but really what we have is space, rather than time. The graph above depicts a linear sequence of noise values in a one-dimensional space, and values are retrieved at a specific x-position. In examples, you will often see a variable named <code>xoff</code> to indicate the x-offset along the noise graph, rather than <code>t</code> for time (as noted in the diagram).</p>
  
  <div data-type="exercise" id="intro_exercise7">
  <h5>Exercise I.7</h5>
  
  <p>In the above random walker, the result of the noise function is mapped directly to the walker’s position. Create a random walker where you instead map the result of the <code>noise()</code> function to a walker's step size.</p>
  </div>
  </section>
  
  <section data-type="sect2" id="_two_dimensional_noise">
  <h3>Two-Dimensional Noise</h3>
  
  <a data-primary="Perlin noise" data-secondary="two-dimensional" data-type="indexterm"></a>
  
  <p>This idea of noise values living in a one-dimensional space is important because it leads right into a discussion of two-dimensional space. Think about this for a moment. With one-dimensional noise, there is a sequence of values in which any given value is similar to its neighbor. Because the values live in one dimension, each has only two neighbors: a value that comes before it (to the left on the graph) and one that comes after it (to the right).</p>
  
  <figure class="two-col-borderless" id="intro_figure10"><img alt="Figure I.10: 1D Noise" src="intro/intro_10.png" />
  <figcaption>Figure I.10: 1D Noise&nbsp;</figcaption>
  </figure>
  
  <figure class="two-col-borderless" id="intro_figure11"><img alt="Figure I.11: 2D Noise" src="intro/intro_11.png" />
  <figcaption>Figure I.11: 2D Noise&nbsp;</figcaption>
  </figure>
  
  <p>Two-dimensional noise works exactly the same way conceptually. The difference of course is that the values don't live along a linear path, but rather sit on a grid. Think of a piece of graph paper with numbers written into each cell. A given value will be similar to all of its neighbors: above, below, to the right, to the left, and along any diagonal.</p>
  
  <p>If you were to visualize this graph paper with each value mapped to the brightness of a color, you would get something that looks like clouds. White sits next to light gray, which sits next to gray, which sits next to dark gray, which sits next to black, which sits next to dark gray, etc.</p>
  
  <figure><img alt="intro ex07" src="intro/intro_ex07.png" />
  <figcaption>&nbsp;</figcaption>
  </figure>
  
  <p>This is why noise was originally invented. If you tweak the parameters and play with color, the resulting images look more like marble or wood or any other organic texture.</p>
  
  <p>Let’s take a quick look at how to implement two-dimensional noise. If you wanted to color every pixel of a canvas randomly, you would need a nested loop, one that accessed each pixel and picked a random brightness. (Note that is p5, the pixels are arranged in an array with 4 spots for each: red, green, blue, and alpha. For details, see <a href="https://youtu.be/nMUMZ5YRxHI">this video tutorial on the pixel array</a>.</p>
  
  <pre data-code-language="java" data-type="programlisting" class="codesplit">
  loadPixels();
  for (let x = 0; x &lt; width; x++) {
    for (let y = 0; y &lt; height; y++) {
      let index = (x + y * width) * 4;
      //{!1} A random brightness!
      let bright = random(255);
      // Setting the red, green, and blue values
      pixels[index    ] = bright;
      pixels[index + 1] = bright;
      pixels[index + 2] = bright;
    }
  }
  updatePixels();</pre>
  
  <p>To color each pixel according to the <code>noise()</code> function, we’ll do exactly the same thing, only instead of calling <code>random()</code> we’ll call <code>noise()</code>.</p>
  
  <pre data-code-language="java" data-type="programlisting" class="codesplit">
     //{.bold} A Perlin noise brightness!
     let bright = map(noise(x, y), 0, 1, 0, 255);</pre>
  
  <p>This is a nice start conceptually—it gives you a noise value for every (<code>x</code>,<code>y</code>) position in a two-dimensional space. The problem is that this won’t have the cloudy quality we want. Jumping from pixel 200 to pixel 201 is too large of a jump through noise. Remember, with one-dimensional noise, I incremented the time variable by 0.01 each frame, not by 1! A pretty good solution to this problem is to just use different variables for the noise arguments. For example, a variable called <code>xoff</code> can be incremented each time <code></code>x increases horizontally, and a <code>yoff</code> variable each time <code>y</code> moves vertically through the nested loops.</p>
  
  <div data-type="example">
  <h5>Example I.7: 2D Perlin noise</h5>
  </div>
  
  <pre data-code-language="java" data-type="programlisting" class="codesplit">
  //{!1 .bold} Start xoff at 0.
  let xoff = 0.0;
  
  for (let x = 0; x &lt; width; x++) {
    //{!1 .bold} For every xoff, start yoff at 0.
    let yoff = 0.0;
  
    for (let y = 0; y &lt; height; y++) {
      //{.bold .code-wide} Use xoff and yoff for noise().
      let bright = map(noise(xoff, yoff), 0, 1, 0, 255);
      // Use x and y for pixel position.
      let index = (x + y * width) * 4;
      // Setting the red, green, and blue values
      pixels[index    ] = bright;
      pixels[index + 1] = bright;
      pixels[index + 2] = bright;
      //{!1 .bold} Increment yoff.
      yoff += 0.01;
    }
    //{!1 .bold} Increment xoff.
    xoff += 0.01;
  }</pre>
  
  <div data-type="exercise" id="intro_exercise8">
  <h5>Exercise I.8</h5>
  
  <p>Play with color, <code>noiseDetail()</code>, and the rate at which <code>xoff</code> and <code>yoff</code> are incremented to achieve different visual effects.</p>
  </div>
  
  <div data-type="exercise" id="intro_exercise9">
  <h5>Exercise I.9</h5>
  
  <p>Add a third argument to noise that increments once per cycle through <code>draw()</code> to animate the two-dimensional noise.</p>
  </div>
  
  <div data-type="exercise" id="intro_exercise10">
  <h5>Exercise I.10</h5>
  
  <p>Use the noise values as the elevations of a landscape. See the screenshot below as a reference.</p>
  
  <figure><img alt="intro exc10" src="intro/intro_exc10.png" />
  <figcaption>intro exc10&nbsp;</figcaption>
  </figure>
  </div>
  
  <p>I’ve examined several traditional uses of Perlin noise in this section. With one-dimensional noise, smooth values were assigned to the position of an object to give the appearance of wandering. With two-dimensional noise, a cloudy pattern was generated with smoothed values on a plane of pixels. It’s important to remember, however, that Perlin noise values are just that—values. They aren’t inherently tied to pixel positions or color. Any example in this book that has a variable could be controlled via Perlin noise. When I model a wind force, its strength could be controlled by Perlin noise. Same goes for the angles between the branches in a fractal tree pattern, or the speed and direction of objects moving along a grid in a flow field simulation.</p>
  
  <figure class="two-col"  data-p5-sketch="https://editor.p5js.org/embed/ryDyKwjUX" id="intro_figure12"><img alt="Figure I.12: Tree with Perlin noise" src="intro/intro_12.png" />
  <figcaption>Figure I.12: Tree with Perlin noise&nbsp;</figcaption>
  </figure>
  
  <figure class="two-col" data-p5-sketch="https://editor.p5js.org/embed/r1hu4OoIm" id="intro_figure13"><img alt="Figure I.13: Flow field with Perlin noise" src="intro/intro_13.png" />
  <figcaption>Figure I.13: Flow field with Perlin noise&nbsp;</figcaption>
  </figure>
  </section>
  </section>
  
  <section data-type="sect1" id="intro_section7">
  <h2>I.7 Onward</h2>
  
  <p>I began this chapter by talking about how randomness can be a crutch. In many ways, it’s the most obvious answer to the kinds of questions we ask continuously—how should this object move? What color should it be? This obvious answer, however, is sometimes a lazy one.</p>
  
  <p>As I finish the introduction, it’s also worth noting that you could just as easily fall into the trap of using Perlin noise as a crutch. How should this object move? Perlin noise! What color should it be? Perlin noise! How fast should it grow? Perlin noise!</p>
  
  <p>The point of all of this is not to say that you should or shouldn’t use randomness. Or that you should or shouldn’t use Perlin noise. The point is that the rules of your system are defined by you, and the larger your toolbox, the more choices you’ll have as you implement those rules. The goal of this book is to fill your toolbox. If all you know is random, then your design thinking is limited. Sure, Perlin noise helps, but you’ll need more. A lot more.</p>
  
  <p>I think we’re ready to begin.</p>
  </section>
  </section>
  